package com.demo.app.service;

import com.demo.app.entity.MyUserDetails;
import com.demo.app.mapper.MyUserDetailsServiceMapper;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyUserDetailsService implements UserDetailsService {

  @Resource
  MyUserDetailsServiceMapper myUserDetailsServiceMapper;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


    //用户基础数据加载
    MyUserDetails myUserDetails = myUserDetailsServiceMapper.findByUserName(username);

    if(myUserDetails == null){
      throw new UsernameNotFoundException("用户名不存在");
    }

    //用户的角色列表
    List<String> roleCodes = myUserDetailsServiceMapper.findRoleByUserName(username);

    //根据角色列表加载当前用户具有的权限
    List<String> authorities =myUserDetailsServiceMapper.findAuthorityByRoleCodes(roleCodes);

    roleCodes = roleCodes.stream()
            .map(rc -> "ROLE_" + rc)
            .collect(Collectors.toList());

    authorities.addAll(roleCodes);

    myUserDetails.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(
            String.join(",",authorities)
    ));

    return myUserDetails;
  }


}
